package com.note.chh.notebook.UI.enjoy;


import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.tools.DateUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.note.chh.notebook.Adapter.DialogMusicAdapter;
import com.note.chh.notebook.Adapter.DialogNewAdapter;
import com.note.chh.notebook.Adapter.DialogRankAdapter;
import com.note.chh.notebook.Adapter.DialogSongAdapter;
import com.note.chh.notebook.Adapter.MusicBgAdapter;
import com.note.chh.notebook.Adapter.MusicLyricAdapter;
import com.note.chh.notebook.Api.Constant;
import com.note.chh.notebook.Model.GetHashModel;
import com.note.chh.notebook.Model.GetMusicInfo;
import com.note.chh.notebook.Model.NewMusicModel;
import com.note.chh.notebook.Model.RankListModel;
import com.note.chh.notebook.Model.SongListModel;
import com.note.chh.notebook.R;
import com.note.chh.notebook.UI.base.BaseActivity;
import com.note.chh.notebook.Uitls.DisplayUtil;
import com.note.chh.notebook.Uitls.ItemDivider;
import com.note.chh.notebook.Uitls.UserUtil;
import com.note.chh.notebook.Uitls.gson.GsonImpl;
import com.note.chh.notebook.Uitls.localFile.bean.AudioItem;
import com.note.chh.notebook.Widget.CircleImageView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

//播放音乐
public class PlayMusicActivity extends BaseActivity implements View.OnClickListener,MediaPlayer.OnCompletionListener{

    private String audio_path,audio_name;
    private MediaPlayer mediaPlayer;
    private SeekBar musicSeekBar;
    private boolean isPlayAudio = false;

    private TextView  tv_musicTotal, tv_musicTime;
    private ImageView mImg_lastest,mImg_pause,mImg_next;
    private TextView mText_musicName,mText_lyric;
    private RelativeLayout mRelative_circle,mRelative_root;
    private ImageView mImage_aci,mImage_musicList,mImage_cp,mImage_back,
            mImage_playStyle,mImage_bg_More;
    private RecyclerView mRecycle_lyric;
    private BaseQuickAdapter musicLyricAdapter;

    private int currentPosition = 0;//当前播放的位置
    private List<AudioItem> musicList;//本地音乐的集合
    private List<RankListModel.SongsBean.ListBean> rankList;//排行榜歌曲集合
    private List<NewMusicModel.DataBean> newList;//新歌榜集合
    private List<SongListModel.SongsBean.ListBean> songList;//歌手的歌曲集合
    private List<Integer> timeList;//每句歌词停靠的时间
    private List<String> lyricList;//歌词
    private ObjectAnimator animator,animator_aci;
    private int mScreenWidth, mScreenHeight;
    private static final int degerss = 30;//旋转的角度
    private static final int duratioon = 400;//唱针移动的时间
    private static final int cpDuration = 25000;//唱片转动一圈的时间
    private CircleImageView mCircleImage;
    private String musicPicUrl = "";//当前播放音乐的专辑图片url
    private int startTime = 0,stopTime = 0;
    private int playStyle = 1;//播放方式   默认1列表循环  2随机播放  3单曲循环
    private int musicBg = 0;//音乐背景图  使用第几张

    private IntentFilter intentFilter;
    private MusicBroadcast musicBroadcast;
    private static final String MUSIC_PAUSE_PLAY = "music.pause.play.action";
    private static final String MUSIC_NEXT = "music.next.action";
    private static final String MUSIC_CLOSE = "music.close.action";
    private static final String MUSIC_OPEN = "music.open.action";
    private static final int MUSIC_NOTIFICATION_ID  = 100;
    private boolean isShowNotification = true;//是否显示通知栏

    private static final int MSG_WHATE_ONE = 1;
    private static final int MSG_WHATE_TWO = 2;
    private static final int MSG_WHATE_THREE = 3;

    private boolean netMusic = false;
    private int songType = 0;//网络歌曲的类型  0表示排行榜   1表示新歌榜   2表示歌手-歌曲
    @Override
    protected int bindLayout() {
        return R.layout.activity_play_music;
    }

    @Override
    public void initView() {
        //注册广播
        intentFilter = new IntentFilter();
        intentFilter.addAction(MUSIC_PAUSE_PLAY);
        intentFilter.addAction(MUSIC_NEXT);
        intentFilter.addAction(MUSIC_CLOSE);
        intentFilter.addAction(MUSIC_OPEN);
        musicBroadcast = new MusicBroadcast();
        registerReceiver(musicBroadcast,intentFilter);


        QMUIStatusBar(PlayMusicActivity.this);

        mScreenWidth = DisplayUtil.getScreenWidth(context);
        mScreenHeight = DisplayUtil.getScreenHeight(context);

        Bundle bundle = getIntent().getExtras();
        netMusic = bundle.getBoolean("netMusic");
        if (!netMusic) {
            audio_path = bundle.getString("musicUrl");
            currentPosition = bundle.getInt("position");
            musicList = ((List<AudioItem>) bundle.getSerializable("musicList"));
        }else{
            songType = bundle.getInt("songType");
            String hash = bundle.getString("hash");
            if (songType==0) {
                rankList = bundle.getParcelableArrayList("rankList");
            } else if (songType==1) {
                newList = bundle.getParcelableArrayList("newList");
            }else if(songType==2){
                songList = bundle.getParcelableArrayList("songList");
            }
            currentPosition = bundle.getInt("position");
            getMusicInfo(hash);
        }

        tv_musicTime = (TextView) findViewById(R.id.tv_musicTime);
        musicSeekBar = (SeekBar) findViewById(R.id.musicSeekBar);
        tv_musicTotal = (TextView) findViewById(R.id.tv_musicTotal);

        mText_musicName = findViewById(R.id.mText_musicName);//歌曲名字
        mImg_lastest = (ImageView) findViewById(R.id.mImg_lastest);//上一首
        mImg_pause = (ImageView) findViewById(R.id.mImg_pause);//暂停、播放
        mImg_next = (ImageView) findViewById(R.id.mImg_next);//下一首
        mRelative_circle = findViewById(R.id.mRelative_circle);//圆形图片父布局
        mCircleImage = findViewById(R.id.mCircleImage);//圆形图片
        mImage_aci = findViewById(R.id.mImage_aci);//耳机样式的图片
        mRelative_root = findViewById(R.id.mRelative_root);
        mImage_musicList = findViewById(R.id.mImage_musicList);//展示dialog音乐列表
        mImage_cp = findViewById(R.id.mImage_cp);//唱片
        mText_lyric = findViewById(R.id.mText_lyric);//歌词
        mImage_back = findViewById(R.id.mImage_back);//返回
        mImage_playStyle = findViewById(R.id.mImage_playStyle);//播放方式
        mRecycle_lyric = findViewById(R.id.mRecycle_lyric);//展示歌词
        mImage_bg_More = findViewById(R.id.mImage_bg_More);//更多背景

        initMusicBg();

        mImage_playStyle.setImageResource(R.drawable.select_music_normal_next);
        //设置唱针的位置
        initNeedle();

        mText_musicName.setSelected(true);//使跑马灯生效
        if (!netMusic) {
            setMusicName(bundle.getString("title"));
        }


        //设置中间圆形图片旋转动画
        animator = ObjectAnimator.ofFloat(mRelative_circle, "rotation", 0f, 360.0f);
        animator.setDuration(cpDuration);
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);

        initListene();

    }


    private void getModel(){


    }

    //初始化音乐背景图
    private void initMusicBg(){
        //取得音乐背景图的位置
        musicBg =  SPUtils.getInstance(Constant.SP_NAME).getInt(Constant.KEY_MUSIC_BG,0);
        if (mbgList == null) {
            mbgList = new ArrayList<>();
            for (int i = 0; i < Constant.mbg.length; i++) {
                mbgList.add(String.valueOf(i));
            }
        }
        mRelative_root.setBackgroundResource(Constant.mbg[musicBg]);
    }

    //init  view 和 监听事件
    private void initListene() {
        mRecycle_lyric.setLayoutManager(new LinearLayoutManager(this));
        mRecycle_lyric.setHasFixedSize(true);
        musicLyricAdapter = new MusicLyricAdapter(R.layout.item_lyric);
        //设置加载动画
//        musicLyricAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRecycle_lyric.setAdapter(musicLyricAdapter);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initPlayer(audio_path);
            }
        }, 30);
        mImg_pause.setOnClickListener(this);
        mImg_lastest.setOnClickListener(this);
        mImg_next.setOnClickListener(this);
        mImage_musicList.setOnClickListener(this);
        mImage_back.setOnClickListener(this);
        mImage_playStyle.setOnClickListener(this);
        mRelative_circle.setOnClickListener(this);
        mImage_cp.setOnClickListener(this);
        mImage_bg_More.setOnClickListener(this);
        musicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser == true) {
                    mediaPlayer.seekTo(progress);
                    UserUtil.dLog(" progress = "+progress);

                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (timeList!=null&&timeList.size()>1) {
                    mhandler.removeMessages(1);
                    startTime = mediaPlayer.getCurrentPosition();
                }
                UserUtil.dLog(" startTime = "+mediaPlayer.getCurrentPosition());
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                UserUtil.dLog(" stopTime = "+mediaPlayer.getCurrentPosition());
                if (timeList!=null&&timeList.size()>1) {
                    stopTime = mediaPlayer.getCurrentPosition();
                    int alltime = 0;
                    for (int i = 0; i < timeList.size(); i++) {
                        if (stopTime>alltime&&stopTime<alltime+timeList.get(i)) {
                            delaytime = alltime+timeList.get(i)-stopTime;
                            mText_lyric.setText(lyricList.get(i).split("\\|")[0]);
                            posNum = i+1;
                            mhandler.sendEmptyMessageDelayed(MSG_WHATE_ONE,delaytime);
                            break;
                        }
                        alltime += timeList.get(i);
                    }
                }
            }
        });
        //查看显示专辑图片
        mImage_cp.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                checkPicture();
                return false;
            }
        });
        musicLyricAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mText_lyric.setVisibility(View.VISIBLE);
                mImage_aci.setVisibility(View.VISIBLE);
                mRelative_circle.setVisibility(View.VISIBLE);
                mImage_bg_More.setVisibility(View.VISIBLE);
                mRecycle_lyric.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = intent.getExtras();
        if (intent!=null&&bundle!=null) {
            netMusic = bundle.getBoolean("netMusic",false);
            if (!netMusic) {
                int position = bundle.getInt("position");
//                if (position!=currentPosition) {
                    musicList = ((List<AudioItem>) bundle.getSerializable("musicList"));
//                    musicList.get(currentPosition).setIsPlay("");
                    audio_path = bundle.getString("musicUrl");
                    currentPosition = position;
                    setMusicName(bundle.getString("title"));
                    lastestOrNextMusic();
//                }
            }else{
                songType = bundle.getInt("songType");
                String hash = bundle.getString("hash");
                if (songType==0) {
                    rankList = bundle.getParcelableArrayList("rankList");
                    currentPosition = bundle.getInt("position");
                    rankList.get(currentPosition).setSqhash("true");
                } else if (songType==1) {
                    newList = bundle.getParcelableArrayList("newList");
                    currentPosition = bundle.getInt("position");
                    newList.get(currentPosition).setSqhash("true");
                } else if (songType==2) {
                    songList = bundle.getParcelableArrayList("songList");
                    currentPosition = bundle.getInt("position");
                    songList.get(currentPosition).setSqhash("true");
                }
                getMusicInfo(hash);
                lastestOrNextMusic();
            }
        }
    }

    //广播
    class MusicBroadcast extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            UserUtil.dLog(" action ="+action);
            switch (action){
                case MUSIC_PAUSE_PLAY://暂停/继续
                    playAudio();
                    setMusicNotification();
                    break;
                case MUSIC_NEXT://下一首
                    if (playStyle==2){//判断是否是随机播放模式
                        randomPlay();
                    }else{
                        nextMusic();
                    }
                    break;
                case MUSIC_CLOSE://关闭notification
                    if (mNotificationManager!=null) {
                        isShowNotification = false;
                        mNotificationManager.cancel(MUSIC_NOTIFICATION_ID);//关闭通知栏上的应用通知
                    }
                    break;
                case MUSIC_OPEN://打开音乐播放页面
                    Intent intent1 = new Intent(getApplicationContext(),PlayMusicActivity.class);
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    startActivity(intent1);
                    BarUtils.setNotificationBarVisibility(false);//关闭通知栏
                    break;
            }
        }
    }

    //设置唱针的位置
    private void initNeedle() {

        int needleWidth = (int) (DisplayUtil.SCALE_NEEDLE_WIDTH * mScreenWidth);
        int needleHeight = (int) (DisplayUtil.SCALE_NEEDLE_HEIGHT * mScreenHeight);

        /*设置手柄的外边距为负数，让其隐藏一部分*/
        int marginTop = (int) (DisplayUtil.SCALE_NEEDLE_MARGIN_TOP * mScreenHeight) * -1;
        int marginLeft = (int) (DisplayUtil.SCALE_NEEDLE_MARGIN_LEFT * mScreenWidth);

        Bitmap originBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.aci);
        Bitmap bitmap = Bitmap.createScaledBitmap(originBitmap, needleWidth, needleHeight, false);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mImage_aci.getLayoutParams();
        layoutParams.setMargins(marginLeft, marginTop, 0, 0);

        int pivotX = (int) (DisplayUtil.SCALE_NEEDLE_PIVOT_X * mScreenWidth);
        int pivotY = (int) (DisplayUtil.SCALE_NEEDLE_PIVOT_Y * mScreenWidth);

        mImage_aci.setPivotX(pivotX);
        mImage_aci.setPivotY(pivotY);
        mImage_aci.setRotation(DisplayUtil.ROTATION_INIT_NEEDLE);
        mImage_aci.setImageBitmap(bitmap);
        mImage_aci.setLayoutParams(layoutParams);

//        UserUtil.dLog("needleWidth ="+needleWidth);

        int bL = needleWidth / 7;//比例中的一份大小
        int h1 = bL * 9;//露出的唱针部分的高度
        int h2 = h1 - bL * 3;//唱片到顶部分割线的距离
        int w1 = (mScreenWidth - bL * 20) / 2;//唱片距离两边的大小
        int w2 = bL * 15;//唱片里面的圆直径
        int w3 = bL * 20;//唱片直径

        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams)mRelative_circle.getLayoutParams();
        params2.height = w3+h2*2;
        mRelative_circle.setLayoutParams(params2);

        ViewGroup.LayoutParams params = mImage_cp.getLayoutParams();
        params.width = w3;
        params.height = w3;
        mImage_cp.setLayoutParams(params);

        ViewGroup.LayoutParams params1 = mCircleImage.getLayoutParams();
        params1.width = w2;
        params1.height = w2;
        mCircleImage.setLayoutParams(params1);


    }

    //设置动画
    private void setAnima(View view,float startDegrees,float endDegrees,long duration){
        animator_aci = ObjectAnimator.ofFloat(view, "rotation", startDegrees, endDegrees);
        animator_aci.setDuration(duration);
        animator_aci.setInterpolator(new LinearInterpolator());
        animator_aci.setRepeatCount(0);
        animator_aci.start();
    }

    //aci离开音乐盘动画
    private void leaveAnima(){
        setAnima(mImage_aci,0,-degerss,duratioon);
    }
    //靠近动画
    private void nearAnima(){
        setAnima(mImage_aci,-degerss,0,duratioon);
    }

    //设置音乐名称
    private void setMusicName(String musicName){
        String[] titles = musicName.split("-");
        if (titles.length>=2) {
            audio_name = titles[0]+" - "+titles[1];
        }else{
            audio_name = titles[0];
        }
        getHash(audio_name);//获取歌曲hash并得到该歌曲详情信息
    }

    @Override
    public void initData() {

    }

    //  通过 Handler 更新 UI 上的组件状态
    public Handler handler = new Handler();
    public Runnable runnable = new Runnable() {
        @Override
        public void run() {
            updateSeekBar();
        }
    };

    //更新进度条 时间
    private void updateSeekBar(){
        try {
            if (mediaPlayer != null) {
                tv_musicTime.setText(DateUtils.timeParse(mediaPlayer.getCurrentPosition()));
                musicSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                musicSeekBar.setMax(mediaPlayer.getDuration());
                tv_musicTotal.setText(DateUtils.timeParse(mediaPlayer.getDuration()));
                handler.postDelayed(runnable, 200);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //初始化音频播放组件
    private void initPlayer(String path) {
        mediaPlayer = new MediaPlayer();
        // 绑定播放完毕监听器
        mediaPlayer.setOnCompletionListener(this);
        if (!netMusic) {
            try {
                mediaPlayer.setDataSource(path);
                mediaPlayer.prepare();
                //设置是否循环播放。
                mediaPlayer.setLooping(false);
                playAudio();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    //点击事件
    @Override
    public void onClick(View v) {

        int i = v.getId();
        if (i == R.id.mImg_pause) {//暂停、播放
            playAudio();
        }
        if (i==R.id.mImg_lastest) {//上一首
            if (playStyle==2){//判断是否是随机播放模式
                randomPlay();
            }else{
                lastestMusic();
            }
        }
        if (i==R.id.mImg_next) {//下一首
            if (playStyle==2){//判断是否是随机播放模式
                randomPlay();
            }else{
//                UserUtil.dLog("---------mImg_next----------");
                nextMusic();
            }
        }
        if (i==R.id.mImage_musicList) {//展示dialog音乐列表
            if (musicBottomDialog==null) {
                showMusicListBottomDialog();
            }else{
                if (songType==0) {
                    if ((rankList!=null&&musicList!=null)||(newList!=null||songList!=null)) {
                        showMusicListBottomDialog();
                        if (netMusic) {
                            musicList=null;
                        }else{
                            rankList = null;
                        }
                        newList = null;
                        songList = null;
                    }else{
                        musicBottomDialog.show();
                    }
                } else if (songType==1) {
                    if ((newList!=null&&musicList!=null)||(rankList!=null||songList!=null)) {
                        showMusicListBottomDialog();
                        if (netMusic) {
                            musicList=null;
                        }else{
                            newList = null;
                        }
                        rankList = null;
                        songList = null;
                    }else{
                        musicBottomDialog.show();
                    }
                } else if (songType==2) {
                    if ((songList!=null&&musicList!=null)||(rankList!=null||newList!=null)) {
                        showMusicListBottomDialog();
                        if (netMusic) {
                            musicList=null;
                        }else{
                            songList = null;
                        }
                        rankList = null;
                        newList = null;
                    }else{
                        musicBottomDialog.show();
                    }
                }
            }
        }
        if (i==R.id.mImage_back) {
            moveTaskToBack(true);
        }
        if (i==R.id.mImage_playStyle) {//播放方式
            if (playStyle==1) {
                playStyle = 2;
//                mediaPlayer.setLooping(false);//取消单曲循环
                mImage_playStyle.setImageResource(R.drawable.select_music_random);
                showToast(PlayMusicActivity.this,"列表随机");
//                Toast.makeText(this,"列表随机",Toast.LENGTH_SHORT).show();
            } else if (playStyle==2) {
                playStyle = 3;
//                mediaPlayer.setLooping(false);//设置单曲循环
                mImage_playStyle.setImageResource(R.drawable.select_music_single);
                showToast(PlayMusicActivity.this,"单曲循环");
//                Toast.makeText(this,"单曲循环",Toast.LENGTH_SHORT).show();
            } else if (playStyle==3) {
                playStyle = 1;
//                mediaPlayer.setLooping(false);//取消单曲循环
                mImage_playStyle.setImageResource(R.drawable.select_music_normal_next);
                showToast(PlayMusicActivity.this,"列表循环");
//                Toast.makeText(this,"列表循环",Toast.LENGTH_SHORT).show();
            }
        }
        if (i==R.id.mRelative_circle||i==R.id.mImage_cp) {//专辑图片界面 - 切换歌词界面
            if (mRecycle_lyric.getVisibility() != View.VISIBLE) {
//                UserUtil.dLog("  mRelative_circle  " );
                mText_lyric.setVisibility(View.GONE);
                mImage_aci.setVisibility(View.GONE);
                mRelative_circle.setVisibility(View.GONE);
                mImage_bg_More.setVisibility(View.GONE);
                mRecycle_lyric.setVisibility(View.VISIBLE);
                setMusicLyricData();
                mhandler.sendEmptyMessage(MSG_WHATE_THREE);
            }
        }
        if (i==R.id.mImage_bg_More) {//更多背景
            if (musicBgBottomDialog==null) {
                showMusicBgBottomDialog();
            }else{
                musicBgBottomDialog.show();
            }
        }
    }

    //设置歌词滚动的集合
    private List<String> solLyricList ;
    private void setMusicLyricData(){
            if (lyricList==null) {
                lyricList = new ArrayList<>();
            }
            if (lyricList.size()==0) {
                lyricList.add(Constant.NoGetLyric+"|0");
            }
            if (solLyricList == null) {
                solLyricList = new ArrayList<>();
            }else{
                solLyricList.clear();
            }
            solLyricList.addAll(lyricList);
            for (int i = 0; i < 5; i++) {
                solLyricList.add(0,"");
            }
            for (int i = 0; i < 6; i++) {
                solLyricList.add(solLyricList.size(),"");
            }
            musicLyricAdapter.setNewData(solLyricList);
    }

    //上一首
    private void lastestMusic(){
        if (!netMusic) {
            if (musicList!=null&&musicList.size()>0) {
                musicList.get(currentPosition).setIsPlay("");//以防对于dialog列表显示的情况，条目上显示的图标没有更新
                if (currentPosition==0) {
                    currentPosition = musicList.size()-1;
                }else{
                    currentPosition -= 1;
                }
                AudioItem audioItem = musicList.get(currentPosition);
                audio_path = audioItem.getPath();
                setMusicName(audioItem.getName());
                lastestOrNextMusic();
            }
        }else{
            if (songType==0) {
                if (rankList!=null&&rankList.size()>0) {
                    rankList.get(currentPosition).setSqhash("");//以防对于dialog列表显示的情况，条目上显示的图标没有更新
                    if (currentPosition==0) {
                        currentPosition = rankList.size()-1;
                    }else{
                        currentPosition -= 1;
                    }
                    lastestOrNextMusic();
                    RankListModel.SongsBean.ListBean listBean = rankList.get(currentPosition);
                    getMusicInfo(listBean.getHash());
                }
            } else if (songType==1) {
                if (newList!=null&&newList.size()>0) {
                    newList.get(currentPosition).setSqhash("");//以防对于dialog列表显示的情况，条目上显示的图标没有更新
                    if (currentPosition==0) {
                        currentPosition = newList.size()-1;
                    }else{
                        currentPosition -= 1;
                    }
                    lastestOrNextMusic();
                    NewMusicModel.DataBean listBean = newList.get(currentPosition);
                    getMusicInfo(listBean.getHash());
                }
            } else if (songType==2) {
                if (songList!=null&&songList.size()>0) {
                    songList.get(currentPosition).setSqhash("");//以防对于dialog列表显示的情况，条目上显示的图标没有更新
                    if (currentPosition==0) {
                        currentPosition = songList.size()-1;
                    }else{
                        currentPosition -= 1;
                    }
                    lastestOrNextMusic();
                    SongListModel.SongsBean.ListBean listBean = songList.get(currentPosition);
                    getMusicInfo(listBean.getHash());
                }

            }
        }
    }

    //下一首
    private void nextMusic(){
        if (!netMusic) {
            if (musicList!=null&&musicList.size()>0) {
                musicList.get(currentPosition).setIsPlay("");//以防对于dialog列表显示的情况，条目上显示的图标没有更新
                if (currentPosition==musicList.size()-1) {
                    currentPosition = 0;
                }else{
                    currentPosition += 1;
                }
                AudioItem audioItem = musicList.get(currentPosition);
                audio_path = audioItem.getPath();
                setMusicName(audioItem.getName());
                lastestOrNextMusic();
            }
        }else{
            if (songType==0) {
                rankList.get(currentPosition).setSqhash("");
                if (rankList!=null&&rankList.size()>0) {
                    if (currentPosition==rankList.size()-1) {
                        currentPosition = 0;
                    }else{
                        currentPosition += 1;
                    }
                    lastestOrNextMusic();
                    RankListModel.SongsBean.ListBean listBean = rankList.get(currentPosition);
                    getMusicInfo(listBean.getHash());
                }
            } else if (songType==1) {
                newList.get(currentPosition).setSqhash("");
                if (newList!=null&&newList.size()>0) {
                    if (currentPosition==newList.size()-1) {
                        currentPosition = 0;
                    }else{
                        currentPosition += 1;
                    }
                    lastestOrNextMusic();
                    NewMusicModel.DataBean listBean = newList.get(currentPosition);
                    getMusicInfo(listBean.getHash());
                }
            } else if (songType==2) {
                songList.get(currentPosition).setSqhash("");
                if (songList!=null&&songList.size()>0) {
                    if (currentPosition==songList.size()-1) {
                        currentPosition = 0;
                    }else{
                        currentPosition += 1;
                    }
                    lastestOrNextMusic();
                    SongListModel.SongsBean.ListBean listBean = songList.get(currentPosition);
                    getMusicInfo(listBean.getHash());
                }
            }
        }
    }

    //上一首、下一首
    private void lastestOrNextMusic(){
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        // 绑定播放完毕监听器
//        mediaPlayer.setOnCompletionListener(this);
        try {
            mediaPlayer.stop();
            // 切歌之前先重置，释放掉之前的资源
            mediaPlayer.reset();
            // 设置播放源
            if (!netMusic) {
                mediaPlayer.setDataSource(audio_path);
                // 开始播放前的准备工作，加载多媒体资源，获取相关信息
                mediaPlayer.prepare();
                mediaPlayer.seekTo(0);
            }else{
                PlayMusicActivity.this.mediaPlayer.release();
                PlayMusicActivity.this.mediaPlayer = null;
            }
//            // 开始播放
//            mediaPlayer.start();
//            //圆形图旋转动画
//            animator.start();
            //
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                animator.pause();//暂停动画
            }
            leaveAnima();
//            nearAnima();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!netMusic) {
            musicSeekBar.setProgress(mediaPlayer.getCurrentPosition());
            musicSeekBar.setMax(mediaPlayer.getDuration());
            mImg_pause.setImageResource(R.drawable.select_music_playing);
        }else{
            mImg_pause.setImageResource(R.drawable.select_music_pause);
        }
        //移除上一首更新歌词的handler发送
        mhandler.removeMessages(MSG_WHATE_ONE);

    }

    //随机播放
    private void randomPlay(){
//        mediaPlayer.setLooping(false);//取消循环播放
        Random random = new Random();
        if (!netMusic) {
            if (musicList!=null) {
                int nextInt = 0;
                do {
                    nextInt = random.nextInt(musicList.size());
                }while (nextInt==currentPosition);
                //以防对于dialog列表显示的情况，条目上显示的图标没有更新
                musicList.get(currentPosition).setIsPlay("");
                currentPosition = nextInt;
                AudioItem audioItem = musicList.get(currentPosition);
                audio_path = audioItem.getPath();
                setMusicName(audioItem.getName());
                lastestOrNextMusic();
            }
        }else{
            if (songType==0) {
                if (rankList!=null) {
                    int nextInt = 0;
                    do {
                        nextInt = random.nextInt(rankList.size());
                    }while (nextInt==currentPosition);
                    //以防对于dialog列表显示的情况，条目上显示的图标没有更新
                    rankList.get(currentPosition).setSqhash("");
                    currentPosition = nextInt;
                    lastestOrNextMusic();
                    RankListModel.SongsBean.ListBean listBean = rankList.get(currentPosition);
                    getMusicInfo(listBean.getHash());
                }
            } else if (songType==1) {
                if (newList!=null) {
                    int nextInt = 0;
                    do {
                        nextInt = random.nextInt(newList.size());
                    }while (nextInt==currentPosition);
                    //以防对于dialog列表显示的情况，条目上显示的图标没有更新
                    newList.get(currentPosition).setSqhash("");
                    currentPosition = nextInt;
                    lastestOrNextMusic();
                    NewMusicModel.DataBean listBean = newList.get(currentPosition);
                    getMusicInfo(listBean.getHash());
                }
            } else if (songType==2) {
                if (songList!=null) {
                    int nextInt = 0;
                    do {
                        nextInt = random.nextInt(songList.size());
                    }while (nextInt==currentPosition);
                    //以防对于dialog列表显示的情况，条目上显示的图标没有更新
                    songList.get(currentPosition).setSqhash("");
                    currentPosition = nextInt;
                    lastestOrNextMusic();
                    SongListModel.SongsBean.ListBean listBean = songList.get(currentPosition);
                    getMusicInfo(listBean.getHash());
                }
            }
        }
    }

    //单曲循环
    private void singleCycle(){
        if (!netMusic) {
            AudioItem audioItem = musicList.get(currentPosition);
            audio_path = audioItem.getPath();
            setMusicName(audioItem.getName());
            lastestOrNextMusic();
        }else{
            lastestOrNextMusic();
            if (songType==0) {
                RankListModel.SongsBean.ListBean listBean = rankList.get(currentPosition);
                getMusicInfo(listBean.getHash());
            } else if (songType==1) {
                NewMusicModel.DataBean listBean = newList.get(currentPosition);
                getMusicInfo(listBean.getHash());
            } else if (songType==2) {
                SongListModel.SongsBean.ListBean listBean = songList.get(currentPosition);
                getMusicInfo(listBean.getHash());
            }
        }
    }

    //播放音频
    private void playAudio() {
        if (mediaPlayer != null) {
            musicSeekBar.setProgress(mediaPlayer.getCurrentPosition());
            musicSeekBar.setMax(mediaPlayer.getDuration());
        }
        playOrPause();
        if (isPlayAudio == false) {
            handler.post(runnable);
        }
    }

    //停止播放
    public void stop(String path) {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop();
                mediaPlayer.reset();
                mediaPlayer.setDataSource(path);
                mediaPlayer.prepare();
                mediaPlayer.seekTo(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //暂停-继续播放
    private int delaytime = 0;//当暂停的时候，当前显示的歌词还能显示的时间
    private int bftime = 0;//当暂停的时候，当前已经播放的时间
    public void playOrPause() {
        try {
            if (mediaPlayer != null) {
                if (mediaPlayer.isPlaying()) {
                    //对于暂停时，歌词相关的一些处理
                    if (timeList!=null&&timeList.size()>1) {
                        mhandler.removeMessages(1);
                        for (int i = 0; i < timeList.size(); i++) {
                            if (i<=posNum-2) {
                                bftime +=  timeList.get(i);
                            }else{
                                break;
                            }
                        }
                        delaytime = timeList.get(posNum-1)-(mediaPlayer.getCurrentPosition()-bftime);
                    }

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//api版本大于19能使用该方法
                        animator.pause();//暂停动画
                    }
                    leaveAnima();
                    mediaPlayer.pause();
                    mImg_pause.setImageResource(R.drawable.select_music_pause);
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//api版本大于19能使用该方法
                        animator.resume();//继续动画
                    }
                    nearAnima();
                    //对于播放时，歌词相关的一些处理
                    if (timeList!=null&&timeList.size()>1) {
                        mhandler.sendEmptyMessageDelayed(MSG_WHATE_ONE,delaytime);
                        delaytime = 0;bftime = 0;
                    }
                    mediaPlayer.start();
                    mImg_pause.setImageResource(R.drawable.select_music_playing);
//                    animator.start();
                }
                if (isShowNotification) {
                    setMusicNotification();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (animator!=null) {
            animator.cancel();//取消动画
            animator = null;
        }
        if (animator_aci!=null) {
            animator_aci.cancel();//取消动画
            animator_aci = null;
        }
        if (mediaPlayer != null && handler != null) {
            handler.removeCallbacks(runnable);
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (musicBottomDialog!=null) {
            musicBottomDialog.cancel();
            musicBottomDialog = null;
        }
        if (handler!=null) {
            handler = null;
        }
        if (mhandler!=null) {
            mhandler.removeMessages(MSG_WHATE_ONE);
            mhandler.removeMessages(MSG_WHATE_TWO);
            mhandler.removeMessages(MSG_WHATE_THREE);
            mhandler = null;
        }
        //销毁Activity时取消注册广播监听器；
        unregisterReceiver(musicBroadcast);
        if (mNotificationManager!=null) {
            mNotificationManager.cancel(MUSIC_NOTIFICATION_ID);//关闭通知栏
        }

    }

    //播放完成时的监听
    @Override
    public void onCompletion(MediaPlayer mp) {
//        mediaPlayer = mp;
        if (playStyle==1) {//列表循环
            //当播放完成时播放下一首
            nextMusic();
        }else if(playStyle==2){//列表随机
            randomPlay();
        }else if(playStyle==3){//单曲循环
            singleCycle();
        }
    }

    //获取歌曲的hash值
    private void getHash(String keyword){
        OkGo.<String>post("http://mobilecdn.kugou.com/api/v3/search/song?format=json&keyword="+keyword+"&page=1&pagesize=1&showtype=1").tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
//                UserUtil.dLog(response.body());
                if (!response.body().isEmpty()) {
                    GetHashModel getHashModel = GsonImpl.get().toObject(response.body(), GetHashModel.class);
                    List<GetHashModel.DataBean.InfoBean> info = getHashModel.getData().getInfo();
                    if (info!=null&&info.size()>0) {
                        String hash = info.get(0).getHash();
                        if (!hash.isEmpty()) {
                            getMusicInfo(hash);
                        }else{
                            mText_lyric.setText(Constant.NoGetLyric);
                            musicPicUrl = "";
                            mCircleImage.setImageResource(R.mipmap.test_img);
                            if (lyricList!=null) {
                                lyricList.clear();
                            }
                            changeMusicAction();
                        }
                    }else {
                        mText_lyric.setText(Constant.NoGetLyric);
                        musicPicUrl = "";
                        mCircleImage.setImageResource(R.mipmap.test_img);
                        if (lyricList!=null) {
                            lyricList.clear();
                        }
                        changeMusicAction();
                    }
                }else{
                    mText_lyric.setText(Constant.NoGetLyric);
                    musicPicUrl = "";
                    mCircleImage.setImageResource(R.mipmap.test_img);
                    if (lyricList!=null) {
                        lyricList.clear();
                    }
                    changeMusicAction();
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                musicPicUrl = "";
                mText_lyric.setText(Constant.ErrorLyric);
                mCircleImage.setImageResource(R.mipmap.test_img);
                if (lyricList!=null) {
                    lyricList.clear();
                }
                changeMusicAction();
                if (NetworkUtils.isConnected()) {//判断网络是否连接
                    showToast(PlayMusicActivity.this, Constant.NOTNETWORKCONNECT);
                }else{//未知错误
                    showToast(PlayMusicActivity.this, Constant.UNKNOKNERROR);
                }
            }
        });
    }

    //获取歌曲详情
    private void getMusicInfo(String hash){
        OkGo.<String>post("http://www.kugou.com/yy/index.php?r=play/getdata&hash="+hash).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
//                UserUtil.dLog("getMusicInfo = "+response.body());
                GetMusicInfo getMusicInfo = GsonImpl.get().toObject(response.body(), GetMusicInfo.class);
                GetMusicInfo.DataBean data = getMusicInfo.getData();
                Glide.with(PlayMusicActivity.this).load(data.getImg()).into(mCircleImage);
                musicPicUrl = data.getImg();
                String lyrics = data.getLyrics();
                if (lyrics!=null&&!lyrics.isEmpty()) {
                    String[] split = data.getLyrics().split("\\n");
                    if (split.length==1) {
                        if (timeList!=null) {timeList.clear();}else{timeList = new ArrayList<>();}
                        if (lyricList!=null) {lyricList.clear();}else{lyricList = new ArrayList<>();}
                        mText_lyric.setText(lyrics.substring(lyrics.indexOf("]")+1,lyrics.length()));
                        lyricList.add(lyrics.substring(lyrics.indexOf("]")+1,lyrics.length())+"|0");
                        posNum = 0;
                        mhandler.sendEmptyMessage(MSG_WHATE_ONE);
                    }else{
                        paraseLyric(split,data.getTimelength());
                    }
                }else{
                    mText_lyric.setText(Constant.NoGetLyric);
                    if (lyricList!=null&&timeList!=null) {
                        timeList.clear();lyricList.clear();
                    }
                    setMusicLyricData();
                }
                if (netMusic) {
                    audio_path = data.getPlay_url();
                    String audio_name = data.getAudio_name();
                    playNetMusic(audio_name);
                }else{
                    changeMusicAction();
                }

            }
            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                musicPicUrl = "";
                mText_lyric.setText(Constant.ErrorLyric);
                mCircleImage.setImageResource(R.mipmap.test_img);
                if (lyricList!=null) {
                    lyricList.clear();
                }
                changeMusicAction();
                if (NetworkUtils.isConnected()) {//判断网络是否连接
                    showToast(PlayMusicActivity.this, Constant.NOTNETWORKCONNECT);
                }else{//未知错误
                    showToast(PlayMusicActivity.this, Constant.UNKNOKNERROR);
                }
            }
        });
    }

    //解析歌词
    private void paraseLyric(String[] split,int timeLong){
        if (timeList==null) {
            timeList = new ArrayList<>();
        }else{
            timeList.clear();
        }
        if (lyricList==null) {
            lyricList = new ArrayList<>();
        }else{
            lyricList.clear();
        }
        int lastTime = 0;//上一句开始的时间
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            int i1 = s.indexOf("[");
            int i2 = s.indexOf("]");
            String s1 = s.substring(i1+1, i2);
            int i3 = Integer.parseInt(s1.substring(0, 2));
            int i4 = Integer.parseInt(s1.substring(3, 5));
            int i5 = Integer.parseInt(s1.substring(6, 8));
            int mstime = i3*60*1000+i4*1000+i5;
            String s5 = s.substring(i2+1, s.length());

//            UserUtil.dLog("s1 = "+s1 +" s2 = "+s2+ " s3 = "+s3+" s4 = "+s4 + " s5 = "+s5);
            if (i==0) {
                lastTime = 0;
                lyricList.add(s5+"|0");
            }else if(i==split.length-1){
                timeList.add(mstime-lastTime);
                lyricList.add(s5+"|0");
                timeList.add(timeLong-lastTime);
            }else{
                timeList.add(mstime-lastTime);
                lyricList.add(s5+"|0");
            }
            lastTime = mstime;
        }
        posNum = 0;
        mhandler.sendEmptyMessage(MSG_WHATE_ONE);
    }

    private int posNum = 0;//当前歌词显示的索引
    Handler mhandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case MSG_WHATE_ONE://歌词匹配
                    setLyric();
                    break;
                case MSG_WHATE_TWO://通知栏bitmap
                    createNotification();
                    break;
                case MSG_WHATE_THREE://切换音乐时的对歌词显示的一个bug处理
                    dealLyricBug();
                    break;
            }
        }
    };

    //歌词匹配
    private void setLyric(){
        if (mRecycle_lyric.getVisibility()==View.VISIBLE) {
            //置顶该条目
            ((LinearLayoutManager)mRecycle_lyric.getLayoutManager()).scrollToPositionWithOffset(posNum,0);
            if (lyricList.size()>1) {
                solLyricList.set(posNum+4,solLyricList.get(posNum+4).split("\\|")[0]+"|0");
                solLyricList.set(posNum+5,solLyricList.get(posNum+5).split("\\|")[0]+"|1");
            }
            musicLyricAdapter.setNewData(solLyricList);
        }
        if (posNum<timeList.size()) {
            mText_lyric.setText(lyricList.get(posNum).split("\\|")[0]);
            mhandler.sendEmptyMessageDelayed(MSG_WHATE_ONE,timeList.get(posNum));
            posNum ++;
        }
    }

    //切换音乐时的对歌词显示的一个bug处理
    private void dealLyricBug(){
        if (mRecycle_lyric.getVisibility()==View.VISIBLE) {
            UserUtil.dLog("");
            ((LinearLayoutManager)mRecycle_lyric.getLayoutManager()).scrollToPositionWithOffset(posNum>0?posNum-1:posNum,0);
            solLyricList.set(posNum+4,solLyricList.get(posNum+4).split("\\|")[0]+"|1");
            musicLyricAdapter.setNewData(solLyricList);
        }
    }

    //切换歌曲时的一些动作
    private void changeMusicAction(){
//        UserUtil.dLog("  changeMusicAction 1 "+posNum);
        if (mediaPlayer!=null&&animator!=null&&animator_aci!=null) {
            mText_musicName.setText(audio_name);
            posNum = 0;
//            UserUtil.dLog("  changeMusicAction 2 "+posNum);
            if (isPlayAudio==true) {
                // 开始播放
                mediaPlayer.start();
                //圆形图旋转动画
                animator.start();
                //唱针靠近
                nearAnima();
            }else{
                //圆形图旋转动画
                animator.start();
                isPlayAudio = true;
            }
            //是否显示通知栏
            if (isShowNotification) {
                setMusicNotification();
            }
            //更新歌词界面
            if (mRecycle_lyric.getVisibility()==View.VISIBLE&&lyricList!=null/*&&lyricList.size()>0*/) {
                setMusicLyricData();
            }
        }
    }


    //播放网络歌曲的一些操作
    private void playNetMusic(String musicName){
            posNum = 0;
            if (!musicName.isEmpty()) {
                String[] split = musicName.split("-");
                if (split.length>1) {
                    mText_musicName.setText(split[1]+" - "+split[0]);
                }else{
                    mText_musicName.setText(musicName);
                }
                audio_name = mText_musicName.getText().toString().trim();
            }
            if (mediaPlayer==null) {
                mediaPlayer = new MediaPlayer();
                // 绑定播放完毕监听器
                mediaPlayer.setOnCompletionListener(this);
            }
//            UserUtil.dLog("   musicName  = "+audio_path);
            try {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setDataSource(this,Uri.parse(audio_path));
                //必须在播放前加载音频文件(异步准备)
                mediaPlayer.prepareAsync();
                //监听：准备完成的监听
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
//                        UserUtil.dLog("  ------setOnPreparedListener------   ");
                        mediaPlayer.start();
                        mImg_pause.setImageResource(R.drawable.select_music_playing);
                        //获取音乐的总时长
                        int duration=mediaPlayer.getDuration();
                        //设置进度条的最大值为音乐的总时长
                        musicSeekBar.setMax(duration);
                        handler.post(runnable);
                        //圆形图旋转动画
                        animator.start();
                        //唱针靠近
                        nearAnima();
                        //是否显示通知栏
                        if (isShowNotification) {
                            setMusicNotification();
                        }
                        //更新歌词界面
                        if (mRecycle_lyric.getVisibility()==View.VISIBLE&&lyricList!=null/*&&lyricList.size()>0*/) {
                            setMusicLyricData();
                        }
                    }
                });
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            }catch (IllegalStateException i){
                if (mediaPlayer==null) {
                    mediaPlayer = new MediaPlayer();
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
    }

    //展示音乐
    private BaseQuickAdapter dialogMusicAdapter;
    private Dialog musicBottomDialog;
    private RecyclerView mRecycleView;
    private void showMusicListBottomDialog(){
        musicBottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_music_list, null);
        mRecycleView = (RecyclerView) contentView.findViewById(R.id.mRecycle_dialogMusic);
        mRecycleView.setLayoutManager(new LinearLayoutManager(this));
        //设置条目分割线
        mRecycleView.addItemDecoration(new ItemDivider().setDividerWith(1).setDividerColor(getResources().getColor(R.color.color_00999999)));
        if (!netMusic) {
            dialogMusicAdapter = new DialogMusicAdapter(R.layout.dialog_item_music_list);
        }else{
            if (songType==0) {
                dialogMusicAdapter = new DialogRankAdapter(R.layout.dialog_item_music_list);
            } else if (songType==1) {
                dialogMusicAdapter = new DialogNewAdapter(R.layout.dialog_item_music_list);
            } else if (songType==2) {
                dialogMusicAdapter = new DialogSongAdapter(R.layout.dialog_item_music_list);
            }
        }
        //设置加载动画
        dialogMusicAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRecycleView.setAdapter(dialogMusicAdapter);
        //
        musicBottomDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                if (!netMusic) {
                    if (musicList!=null&&musicList.size()>0) {
                        if (mediaPlayer!=null) {
                            AudioItem audioItem = musicList.get(currentPosition);
                            audioItem.setIsPlay("1");
                        }
                        dialogMusicAdapter.setNewData(musicList);

                    }
                }else{
                    if (songType==0) {
                        if (rankList!=null&&rankList.size()>0) {
                            if (mediaPlayer!=null) {
                                RankListModel.SongsBean.ListBean listBean = rankList.get(currentPosition);
                                listBean.setSqhash("true");
                            }
                            dialogMusicAdapter.setNewData(rankList);
                        }
                    } else if (songType==1) {
                        if (newList!=null&&newList.size()>0) {
                            if (mediaPlayer!=null) {
                                NewMusicModel.DataBean listBean = newList.get(currentPosition);
                                listBean.setSqhash("true");
                            }
                            dialogMusicAdapter.setNewData(newList);
                        }
                    } else if (songType==2) {
                        if (songList!=null&&songList.size()>0) {
                            if (mediaPlayer!=null) {
                                SongListModel.SongsBean.ListBean listBean = songList.get(currentPosition);
                                listBean.setSqhash("true");
                            }
                            dialogMusicAdapter.setNewData(songList);
                        }
                    }
                }
                mRecycleView.scrollToPosition(currentPosition);
            }
        });
        musicBottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        layoutParams.height = getResources().getDisplayMetrics().heightPixels/7*4;
        contentView.setLayoutParams(layoutParams);
        musicBottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        musicBottomDialog.setCanceledOnTouchOutside(true);
        musicBottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        musicBottomDialog.show();
        mRecycleView.scrollToPosition(currentPosition);

        dialogMusicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (position!=currentPosition) {
                    if (!netMusic) {
                        if (musicList!=null) {
                            AudioItem audioItem_old = musicList.get(currentPosition);
                            currentPosition = position;
                            AudioItem audioItem_cur = musicList.get(position);
                            audioItem_old.setIsPlay("");
                            audioItem_cur.setIsPlay("1");
                            audio_path = audioItem_cur.getPath();
                            setMusicName(audioItem_cur.getName());
                            lastestOrNextMusic();
                            dialogMusicAdapter.setNewData(musicList);
                            mRecycleView.scrollToPosition(currentPosition);
                        }
                    }else{
                        if (songType==0) {
                            if (rankList!=null) {
                                RankListModel.SongsBean.ListBean listBean = rankList.get(currentPosition);
                                currentPosition = position;
                                RankListModel.SongsBean.ListBean listBean1 = rankList.get(position);
                                listBean.setSqhash("");
                                listBean1.setSqhash("true");
                                lastestOrNextMusic();
                                getMusicInfo(listBean1.getHash());
                                dialogMusicAdapter.setNewData(rankList);
                                mRecycleView.scrollToPosition(currentPosition);
                            }
                        } else if (songType==1) {
                            if (newList!=null) {
                                NewMusicModel.DataBean listBean = newList.get(currentPosition);
                                currentPosition = position;
                                NewMusicModel.DataBean listBean1 = newList.get(position);
                                listBean.setSqhash("");
                                listBean1.setSqhash("true");
                                lastestOrNextMusic();
                                getMusicInfo(listBean1.getHash());
                                dialogMusicAdapter.setNewData(newList);
                                mRecycleView.scrollToPosition(currentPosition);
                            }
                        } else if (songType==2) {
                            if (songList!=null) {
                                SongListModel.SongsBean.ListBean listBean = songList.get(currentPosition);
                                currentPosition = position;
                                SongListModel.SongsBean.ListBean listBean1 = songList.get(position);
                                listBean.setSqhash("");
                                listBean1.setSqhash("true");
                                lastestOrNextMusic();
                                getMusicInfo(listBean1.getHash());
                                dialogMusicAdapter.setNewData(songList);
                                mRecycleView.scrollToPosition(currentPosition);
                            }
                        }
                    }
                }
            }
        });
    }

    //选择背景
    private BaseQuickAdapter musicBgAdapter;
    private Dialog musicBgBottomDialog;
    private RecyclerView mRecycle_bgMore;
    private List<String> mbgList;
    private void showMusicBgBottomDialog(){

        musicBgBottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_music_bg, null);
        mRecycle_bgMore = (RecyclerView) contentView.findViewById(R.id.mRecycle_bgMore);
        mRecycle_bgMore.setLayoutManager(new GridLayoutManager(this,4));
        //设置条目分割线
        mRecycle_bgMore.addItemDecoration(new ItemDivider().setDividerWith(1).setDividerColor(getResources().getColor(R.color.translucent)));
        musicBgAdapter = new MusicBgAdapter(R.layout.dialog_item_music_bg);
        //设置加载动画
//        musicBgAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRecycle_bgMore.setAdapter(musicBgAdapter);
        musicBgAdapter.setNewData(mbgList);

        musicBgBottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        if (mbgList!=null&&mbgList.size()>8) {
            layoutParams.height = SizeUtils.dp2px(130*2);
        }
        contentView.setLayoutParams(layoutParams);
        musicBgBottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        musicBgBottomDialog.setCanceledOnTouchOutside(true);
        musicBgBottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        musicBgBottomDialog.show();

        musicBgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mRelative_root.setBackgroundResource(Constant.mbg[position]);
                SPUtils.getInstance(Constant.SP_NAME).put(Constant.KEY_MUSIC_BG,position);
                musicBgAdapter.setNewData(mbgList);
            }
        });
    }

    //长按查看图片
    private void checkPicture(){
        if (musicPicUrl.isEmpty()) {
            showToast(PlayMusicActivity.this,"当前没有匹配到该专辑图片");
        }else{
            Intent intent = new Intent(this,CheckMusicPictureActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("picUrl",musicPicUrl);
            bundle.putString("picName","/"+audio_name+".png");
            bundle.putString("picFolder",Constant.imageSaveFolder);
            intent.putExtras(bundle);
//            startActivity(CheckMusicPictureActivity.class,bundle);
            startActivity(intent);
            overridePendingTransition(R.anim.scale_in, R.anim.alpha_out);
        }
    }

    //不销毁activity
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //音乐自定义通知栏
    private RemoteViews views;
    private void setMusicNotification(){
        views = new RemoteViews(getPackageName(),R.layout.notification_music); //自定义的布局视图
        //按钮点击事件：
        PendingIntent ppIntent = PendingIntent.getBroadcast(this,1,new Intent(MUSIC_PAUSE_PLAY),PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.mImage_playing,ppIntent); //点击的id，点击事件

        PendingIntent nextIntent = PendingIntent.getBroadcast(this,1,new Intent(MUSIC_NEXT),PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.mImage_next,nextIntent); //点击的id，点击事件

        PendingIntent closeIntent = PendingIntent.getBroadcast(this,1,new Intent(MUSIC_CLOSE),PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.mImage_close,closeIntent); //点击的id，点击事件

        PendingIntent openIntent1 = PendingIntent.getBroadcast(this,1,new Intent(MUSIC_OPEN),PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.mLinear_song,openIntent1);

        PendingIntent openIntent2 = PendingIntent.getBroadcast(this,1,new Intent(MUSIC_OPEN),PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.mImage_pic,openIntent2);

        setBitmap();
        if (!audio_name.isEmpty()) {
            String[] split = audio_name.split("-");
            if (split.length>1) {
                views.setTextViewText(R.id.mText_songName,split[0]);
                views.setTextViewText(R.id.mText_songer,split[1]);
            }else{
                views.setTextViewText(R.id.mText_songName,split[0]);
                views.setTextViewText(R.id.mText_songer,"");
            }
        }
    }

    private NotificationManager mNotificationManager;
    private void createNotification(){
        //创建通知：
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContent(views)//设置布局
                .setOngoing(true)//常驻通知
                //如果不设置大图标，则小图标会显示在大图标的位置
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.test_img))
                .setSmallIcon(R.mipmap.ic_launcher) //设置小图标
                .setTicker("通知来了") //设置提示
                .setPriority(Notification.PRIORITY_MAX) //设置优先级
                .setWhen(System.currentTimeMillis()) //设置展示时间
                .setShowWhen(false)//不显示时间
                .setContentIntent(PendingIntent.getBroadcast(this,2,new Intent("action.view"),PendingIntent.FLAG_UPDATE_CURRENT));//设置视图点击事件

        mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        mNotificationManager.notify(MUSIC_NOTIFICATION_ID,mBuilder.build());//显示通知： 当前notificationid，当前notification
//        mNotificationManager.cancel(MUSIC_NOTIFICATION_ID);//关闭通知栏
//        UserUtil.dLog(" setMusicNotification  " );
    }

    private void setBitmap(){
        if (mediaPlayer.isPlaying()) {
            UserUtil.dLog(" isPlaying 1");
            views.setImageViewResource(R.id.mImage_playing,R.mipmap.note_btn_pause_white);
        }else{
            views.setImageViewResource(R.id.mImage_playing,R.mipmap.note_btn_play_white);
            UserUtil.dLog(" isPlaying 2");
        }
//        UserUtil.dLog(" setImageViewResource  " );
        OkGo.<Bitmap>get(musicPicUrl).tag(this).execute(new BitmapCallback() {
            @Override
            public void onSuccess(Response<Bitmap> response) {
//                UserUtil.dLog(" setBitmap  " +(response.body()==null));
                views.setImageViewBitmap(R.id.mImage_pic,response.body());
                mhandler.sendEmptyMessage(MSG_WHATE_TWO);
            }
        });
    }

}
